<template>
  <div class="self-dailog">
    <van-popup v-model="dialogVisible" round closeable position="bottom" :style="{ height: '80vh', width: '100%' }">
      <div class="self-address-dailog">
        <div class="self-address-title">
          {{fromShopCar ? '查看' : '请选择'}}<span v-if="shipType == 4">自提</span><span v-else>门店配送</span>地址
        </div>

        <div class="self-address-choose clearfix" @click="showAreaPop = true">
          <span class="fl">选择地址</span>
          <!-- <span class="addr-info">{{ selectAddressTxt }}</span> -->
          <span class="fl" style="margin-left: 10px;">
            <wx-picker mode="multiSelector" :range="multiArray" @columnchange="columnchange" :value="multiIndex" @change='pickchange'>
              <div class='addr-info'>
                <span>{{ selectAddressTxt}}</span>
              </div>
            </wx-picker>
          </span>
        </div>

        <div class="self-address-wrap">
          <div class="tips">推荐距离最近的<span v-if="shipType == 4">自提</span><span v-else>门店配送</span>地址</div>
          <!--地址列表-->

          <div class="box-wrap">
            <van-radio-group
              :disabled="fromShopCar"
              icon-size="16" color="#CCCCCC" checked-color="#F20B22" direction="horizontal" v-model="addressId">
              <div
                v-for="(item, index) in addressList"
                @click="handleClickAddrChoose(item)"
                :key="item.self_address_id"
                class="self-address-wrap-item">
                <van-radio  :name="item.self_address_id">
                  <div class="item-info">
                    <div class="item-info-user">
                      <span class="name">{{ item.name }}</span>
                      <span class="tel" v-if="storeHideMobile==0">{{ item.phone || item.mobile }}</span>
                      <span class="name" v-else>&nbsp;&nbsp;{{ item.shop_name }}</span>
                    </div>
                    <div class="item-info-address">{{ item.province_city_area }} {{ item.address }}</div>
                    <div class="item-info-distance" v-if="item.distance">距离您{{ item.distance }} km</div>
                  </div>
                </van-radio>
              </div>

            </van-radio-group>
          </div>

        </div>
      </div>
    </van-popup>

    <!-- <map-area :visible.sync="showAreaPop" @onSelect="handleConfirm"></map-area> -->
  </div>

</template>

<script>
/**
   * @Author: yqe@360shop.cn
   * @Date: 2020-05-28 20:45:34
 * @Last Modified by: zhangmeng
 * @Last Modified time: 2020-07-30 23:50:27
   */
import Vue from 'vue'
import { Popup, RadioGroup, Radio, Dialog } from 'vant'

import { getProvince, getCity, getArea } from '@/api/login'

Vue.use(Dialog)
Vue.use(Radio).use(RadioGroup)
Vue.use(Popup)
// import mapArea from '@/components/mapArea'

import { selfAddressCount } from '@/api/order/order'

export default Vue.extend({
  name: 'index',
  components: {
    // mapArea
  },
  data() {
    return {
      multiArray: [], // 三维数组数据
      multiIndex: [0, 0, 0], // 默认的下标
      step: 0, // 默认显示请选择
      provinceList: [],
      provinceArr: [],
      currnetProvinceKey: '',
      cityArr: [],
      cityList: [],
      currnetCityKey: '',
      areaArr: [],
      areaList: [],
      currnetAreaKey: '',
      areaBtnTextEdit: '',
      dialogVisible: false,
      showAreaPop: false,
      addressId: '',
      selectAddressTxt: '请选择省市区',
      addressList: [], // 地址列表
      addressListBefore: [], // 上一次的地址列表
      postData: {
        scanCode: '',
        addressId: '',
        province_id: '',
        city_id: '',
        area_id: '',
        latitude: '',
        longitude: '',
        address_id: '',
        item_ids: [],
        type: '',
        goods_info: {}
      }
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    shipType: {
      type: String
    },
    buyLists: {
      type: Array
    },
    latitude: {
      type: [Number, String]
    },
    longitude: {
      type: [Number, String]
    },
    selectLastLocation: {
      type: [Number, String]
    },
    storeHideMobile: {
      type: [Number, String]
    },
    itemId: {
      type: [Number, String]
    },
    fromShopCar: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    dialogVisible(val) {
      this.$emit('update:visible', val)
    },
    visible(val) {
      this.dialogVisible = val
    },
    latitude() {
      if (this.shipType == 4 || this.shipType == 5) {
        this.selfAddressCountFn('auto')
      }
    },
    addressLatitude() {
      if (this.shipType == 5) {
        this.selfAddressCountFn('auto')
      }
    },
    shipType(val) {
      if (val == 4 || val == 5) {
        this.selfAddressCountFn('auto')
      }
    },
    // 来自购物车监听选择不同商品
    itemId() {
      if (this.shipType == 4 || this.shipType == 5) {
        this.selfAddressCountFn('auto')
      }
    }
  },
  mounted() {
      this.getProvinceFn()
  },
  methods: {
    columnchange(e) {
      // console.log(e.detail) // {column: 2, value: 1}
      const column = e.detail.column // 当前改变的列
      const data = {
        multiIndex: JSON.parse(JSON.stringify(this.multiIndex)),
        multiArray: JSON.parse(JSON.stringify(this.multiArray))
      }
      data.multiIndex[column] = e.detail.value
      switch (e.detail.column) { // 此时的改变列数
        case 0:
          var currentProvinceKey = this.provinceList[e.detail.value].province_id
          this.getCityFn({ province_id: currentProvinceKey }) // 获取当前key下面的市级数据
          data.multiIndex[1] = 0 // 将市默认选择第一个
          data.multiIndex[2] = 0
          break
        case 1:
          var currentCitykey = this.cityList[e.detail.value].city_id
          this.getAreaFn({ city_id: currentCitykey }) // 获取门店
          data.multiIndex[2] = 0 // 门店默认为第一个
          break
      }
      this.multiIndex = data.multiIndex
      this.multiArray = data.multiArray
    },
    pickchange(e) { // picker发送选择改变时候触发 通过e.detail.value获取携带的值
      // console.log(e.detail.value) //   [0,1,2]
      this.multiIndex = e.detail.value // 直接更新即可

      this.selectAddressTxt = this.provinceList[this.multiIndex[0]].province_name + this.cityList[this.multiIndex[1]].city_name + this.areaList[this.multiIndex[2]].area_name

      this.postData.province_id = this.provinceList[this.multiIndex[0]].province_id
      this.postData.city_id = this.cityList[this.multiIndex[1]].city_id
      this.postData.area_id = this.areaList[this.multiIndex[2]].area_id

      this.selfAddressCountFn('search')
    },
    /**
       * 获取省份接口
       */
    getProvinceFn(data) {
      getProvince(data).then((res) => {
        if (res.status == 1) {
          const resp = res.data
          // resp.forEach(item => {
          //   item.text = item.province_name
          // })
          // const obj = { text: '选择省份' }
          // resp.unshift(obj)
          // this.provinceList = resp
          const provinceList = [...resp] // 放在一个数组里面
          const provinceArr = resp.map(item => item.province_name) // 获取数据里面的value值，就是只用数据的名称
          this.multiArray = [provinceArr, [], []] // 更新三维数组 更新后长这样 [['江苏省', '福建省'],[],[]]
          this.provinceList = provinceList // 省级原始数据
          this.provinceArr = provinceArr // 省级所有的名称
          const defaultCode = this.provinceList[0].province_id // 使用第一项当作参数获取市级数据
          if (defaultCode) {
            this.currnetProvinceKey = defaultCode // 保存在当前的省级key
            this.getCityFn({ province_id: defaultCode }) // 获取市级数据
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    /**
       * 获取城市接口
       */
    getCityFn(data) {
      getCity(data).then((res) => {
        this.loading = false
        if (res.status == 1) {
          const resp = res.data
          // resp.forEach(item => {
          //   item.text = item.city_name
          // })
          // const obj = { text: '选择城市' }
          // resp.unshift(obj)
          // this.cityList = resp
          const cityArr = resp.map(item => item.city_name)
          const cityList = [...resp]
          this.multiArray = [this.provinceArr, cityArr, []], // 更新三维数组 更新后长这样 [['江苏省', '福建省'], ['徐州市'], []]
          this.cityList = cityList, // 保存下市级原始数据
          this.cityArr = cityArr // 市级所有的名称
          const defaultCode = this.cityList[0].city_id // 用第一个获取门店数据
          if (defaultCode) {
            this.currnetCityKey = defaultCode // 存下当前选择的城市key
            this.getAreaFn({ city_id: defaultCode }) // 获取门店数据
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    /**
       * 获取地区接口
       */
    getAreaFn(data) {
      getArea(data).then((res) => {
        this.loadingArea = false
        if (res.status == 1) {
          const resp = res.data
          // resp.forEach(item => {
          //   item.text = item.area_name
          // })
          // const obj = { text: '选择区域' }
          // if (resp.length > 0) resp.unshift(obj)
          // this.areaList = resp
          const areaArr = resp.map(item => item.area_name)
          const areaList = [...resp]
          this.multiArray = [this.provinceArr, this.cityArr, areaArr], // 更新三维数组 更新后长这样 [['江苏省', '福建省'], ['徐州市'], []]
          this.areaList = areaList, // 保存下市级原始数据
          this.areaArr = areaArr // 市级所有的名称
          const defaultCode = this.areaList[0].area_id // 用第一个获取门店数据
          if (defaultCode) {
            this.currnetAreaKey = defaultCode // 存下当前选择的城市key
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    handleClickAddrChoose(item) {
      this.$emit('getSelfAddressDialog', item)
    },
    /**
       * 省市区地址的确认
       */
    handleConfirm(val) {
      this.selectAddressTxt = `${val.province_name} ${val.city_name ? val.city_name : ''} ${val.area_name ? val.area_name : ''}`
      this.showAreaPop = false
      // province_id city_id area_id
      this.postData.province_id = val.province_id
      this.postData.city_id = val.city_id
      this.postData.area_id = val.area_id
      this.selfAddressCountFn('search')
    },
    /**
       * 关闭弹窗
       */
    handleCloseDialog() {
      this.dialogVisible = false
    },
    /**
       * 自提地址列表
       */
    selfAddressCountFn(type) {
      const ids = []
      const buyLists = this.buyLists
      const goods_info = {}
      buyLists.forEach((item) => {
        ids.push(item.item_id)
        goods_info[item.item_id] = {
          sku_id: item.sku_id,
          num: item.num
        }
      })
      this.postData.goods_info = goods_info
      this.postData.item_ids = ids
      this.postData.latitude = this.latitude
      this.postData.longitude = this.longitude
      this.$loadingWrap.show()
      // // console.log(this.buyLists, 11111)
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 50000)
      this.postData.type = this.shipType
      // console.log(this.postData, 'this.postData')
      selfAddressCount(this.postData).then((res) => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          if (res.data.errorMsg) {
            // this.$Error(res.data.errorMsg)
            Dialog.confirm({
              className: 'common-confirm',
              title: '',
              message: res.data.errorMsg,
              confirmButtonText: '分开结算'
            }).then(() => {
                wx.navigateBack({
                  delta: 1
                })
            })
            return false
          }
          this.addressListBefore = res.data.before
          if (res.data.is_priority_store == 1) { // 上级门店自提 默认展示不打开弹层
            this.addressList[0] = res.data.priority_store
            this.$emit('getSelfAddressDialog', res.data.priority_store)
            this.dialogVisible = false
          } else {
            this.addressList = res.data.recommend
            // if (res.data.before && res.data.before.length > 0 && this.selectLastLocation) { // 已选过门店
            //   this.$emit('getSelfAddressDialog', res.data.before[0])
            //   this.dialogVisible = false
            // } else {
            //   this.$emit('getSelfAddressDialog', {})
            //   this.dialogVisible = true
            // }
          }
          // 如果来自购物车 默认显示
          if (this.fromShopCar) {
            this.dialogVisible = true
          }
          const dataTimeArr = [ // 日期选择组件需要的格式
            { values: res.data.month_item_list ? res.data.month_item_list : [] },
            { values: res.data.store_reservation_service_time ? res.data.store_reservation_service_time : [] }
          ]
          this.$emit('getDateTime', dataTimeArr)
        } else {
          // if (type == 'search') {
          //   this.dialogVisible = true
          // } else {
          //   this.dialogVisible = false
          // }
          this.$Error(res.data.msg)
        }
        if (type == 'search') {
          setTimeout(() => {
            this.dialogVisible = true
          }, 10)
        }
      })
    },
    /**
       * 弹窗中的输入框失去焦点时页面复原
       */
    blurEvent() {
      window.scroll(0, 0)
    }
  }
})
</script>

<style lang="scss">
  .self-address-dailog{
    width: 100%;
    min-height: 100%;
    background: #F7F7F7;
    padding-bottom: 20px;
    .self-address{
      &-title{
        font-size: 30px;
        color: #333;
        text-align: center;
        font-weight: bold;
        background: #fff;
      }
      &-choose{
        padding: 0 24px;
        font-size: 26px;
        color: #333;
        background: #fff;
        display: flex;
        align-items: center;
        .addr-info{
          color: #666;
        }
      }
      &-wrap{
        padding: 0 25px;
        .tips{
          line-height: 76px;
          height: 76px;
        }
        .box-wrap{

        }
        &-item{
          background: #fff;
          padding: 24px;
          border-radius: 20px;
          margin-bottom: 20px;
          width: 100%;
          .item-info{
            &-user{
              font-size: 32px;
              color: #333;
              font-weight: bold;
              margin-bottom: 0;
              // TODO 优化
              line-height: 40px;
            }
            &-address{
              font-size: 26px;
              color: #999;
              line-height: 38px;
            }
            &-distance{
              margin-top:8px;
              font-size:24px;
              color:#666;
            }
          }
        }
      }
    }
  }
</style>
